//创建用户相关的小仓库
import { defineStore } from 'pinia';
//引入接口
import { reqLogin, reqLogout, reqUserInfo } from '@/api/user';
import type { loginFormData, commonResponseData } from '@/api/user/type';
import type { UserState } from './types/type';
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token';
import request from '@/utils/request';

//创建用户小仓库
const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      userName: '',
      userInfo: {},
      tenantInfo: {},
    };
  },
  //异步|逻辑的地方
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      const searchState = {}
      //登录请求
      const result: commonResponseData = await request.post('/auth/login', {data: searchState});
      //登录请求:成功200->token
      //登录请求:失败201->登录失败错误的信息
      if (result.code === 200) {
        //pinia仓库存储一下token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data.token as string;
        //本地存储持久化存储一份
        SET_TOKEN(result.data.token as string);
        //能保证当前async函数返回一个成功的promise
        return Promise.resolve(result);
      } else {
        return Promise.reject(result);
      }
    },
    //获取用户信息方法
    async getUserInfo() {
      try {
        //获取用户信息进行存储仓库当中[用户头像、名字]
        const result: commonResponseData = await reqUserInfo();
        //如果获取用户信息成功，存储一下用户信息
        if (result.code === 200) {
          this.userName = result.data.user.userName;
          this.userInfo = result.data.user;
          this.tenantInfo = result.data.tenantInfo;
          return 'ok';
        } else {
          return Promise.reject('获取用户信息失败');
        }
      } catch (error: any) {
        return Promise.reject(error.message || '获取用户信息失败');
      }
    },
    //退出登录
    async userLogout() {
      const clearStore = () => {
        this.token = '';
        this.userName = '';
        this.userInfo = '';
        this.tenantInfo = '';
        REMOVE_TOKEN();
      };
      //退出登录请求
      try {
        const res = await reqLogout();
        clearStore();
        return res;
      } catch (err) {
        clearStore();
        return err;
      }
    },
    userLocalLogout() {
      //退出本地保存的token信息，不用发请求，否则会使服务器token过期
      this.token = '';
      this.userName = '';
      this.userInfo = '';
      REMOVE_TOKEN();
    },
  },
  getters: {},
});
//对外暴露获取小仓库方法
export default useUserStore;
